﻿using System;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace GLLog.Comms
{
    /// <summary>
    /// 客户端写日志操作
    /// </summary>
    public class CliWriteLog
    {
        private static object locker = new object();
        private StreamWriter sw = null;

        #region 缓存DB日志处理
        /// <summary>
        /// 缓存DB日志处理
        /// </summary>
        public void WirteCacheLogDB()
        {
            string[] TranSQL = null;
            try
            {
                TranSQL = LogCacheTxtDB();
                if (TranSQL != null)
                {
                    MSSQL.SqlOp DB = new MSSQL.SqlOp();
                    DB.ExecuteSqlTran(TranSQL, 30);
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            finally
            {
                TranSQL = null;
            }
        }
        private string[] LogCacheTxtDB()
        {
            string[] TranSQL = null;
            try
            {
                lock (locker)
                {
                    TranSQL = new string[DataEntity.CliData.ee.Count];
                    for (int i = 0; i < DataEntity.CliData.ee.Count; i++)
                    {
                        TranSQL[i] = "insert into tLog (IP,Level,Logger,LogMessage,Exception,AddTime,Interval,Count) values ('" + DataEntity.CliData.ee[i].IP + "','" + DataEntity.CliData.ee[i].Level + "','" + DataEntity.CliData.ee[i].Logger + "','" + DataEntity.CliData.ee[i].LogMessage + "','" + DataEntity.CliData.ee[i].Exception + "','" + DataEntity.CliData.ee[i].AddTime + "'," + DataEntity.CliData.ee[i].Interval + "," + DataEntity.CliData.ee[i].Count + ")";
                    }
                    DataEntity.CliData.ee.RemoveRange(0, DataEntity.CliData.ee.Count);
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            return TranSQL;
        }
        #endregion

        #region 缓存文件日志处理
        /// <summary>
        /// 缓存文件日志处理
        /// </summary>
        public void WirteCacheLogFile()
        {
            lock (locker)
            {
                string FileTxt = "";
                for (int i = 0; i < DataEntity.CliData.ee.Count; i++)
                {
                    FileTxt += "时间-" + DataEntity.CliData.ee[i].AddTime + "间隔" + DataEntity.CliData.ee[i].Interval / 1000 + "秒，发送信息" + DataEntity.CliData.ee[i].Count + "条" + "：" + DataEntity.CliData.ee[i].IP + "-" + DataEntity.CliData.ee[i].Logger + "-" + "记录" + DataEntity.CliData.ee[i].Level + "信息内容" + DataEntity.CliData.ee[i].LogMessage + DataEntity.CliData.ee[i].Exception;
                }
                DataEntity.CliData.ee.RemoveRange(0, DataEntity.CliData.ee.Count);
                if (FileTxt != "")
                {
                    sw = new StreamWriter(Client.Start.LogFilePath + @"\" + DateTime.Now.ToString("yyyymmddhh") + ".log", true, Encoding.Default);
                    try
                    {
                        sw.Write(FileTxt);
                    }
                    catch (Exception ex)
                    {
                        throw (new Exception(ex.Message));
                    }
                    finally
                    {
                        sw.Close();
                        sw.Dispose();
                    }
                }
            }
        }
        #endregion

        #region 缓存远程服务日志处理
        /// <summary>
        /// 缓存远程服务日志处理
        /// </summary>
        public void WirteCacheLogRemotServer()
        {
            if (DataEntity.CliData.ee.Count > 0)
            {
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    byte[] b;
                    lock (locker)
                    {
                        Comms c = new Comms();
                        b = c.SerializeBinary(DataEntity.CliData.ee);
                    }
                    Net.Protocol p = new Net.Protocol();
                    s.Connect(Client.Start.RemotServerIP, Client.Start.RemotServerPort);
                    s.Send(p.MarkPack(b));
                    lock (locker)
                    {
                        DataEntity.CliData.ee.RemoveRange(0, DataEntity.CliData.ee.Count);
                    }
                }
                catch (Exception ex)
                {
                    throw (new Exception(ex.Message));
                }
                finally
                {
                    s.Disconnect(false);
                    s.Close();
                }
            }
        }
        #endregion

        #region 非缓存DB日志处理
        /// <summary>
        /// 非缓存DB日志处理
        /// </summary>
        public void WirteLogDB(string MIP, string MLevel, string MLogger, string MLogMessage, string MException, DateTime MAddTime)
        {
            MSSQL.SqlOp DB = new MSSQL.SqlOp();
            DB.ExecuteNonQuery("insert into tLog (IP,Level,Logger,LogMessage,Exception,AddTime,Interval,Count) values ('" + MIP + "','" + MLevel + "','" + MLogger + "','" + MLogMessage + "','" + MException + "','" + MAddTime + "',0,1)");
        }
        #endregion

        #region 非缓存文件日志处理
        /// <summary>
        /// 非缓存文件日志处理
        /// </summary>
        public void WirteLogFile(string MIP, string MLevel, string MLogger, string MLogMessage, string MException, DateTime MAddTime)
        {
            sw = new StreamWriter(Client.Start.LogFilePath + @"\" + DateTime.Now.ToString("yyyymmddhh") + ".log", true, Encoding.Default);
            string FileTxt = "时间-" + MAddTime + "，发送信息1条" + "：" + MIP + "-" + MLogger + "-" + "记录" + MLevel + "信息内容：" + MLogMessage + MException;
            try
            {
                sw.Write(FileTxt);
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
        }
        #endregion

        #region 非缓存远程服务日志处理
        /// <summary>
        /// 非缓存远程服务日志处理
        /// </summary>
        public void WirteLogRemotServer(string MIP, string MLevel, string MLogger, string MLogMessage, string MException, DateTime MAddTime)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                Net.Protocol p = new Net.Protocol();
                if (!s.Connected)
                {
                    s.Connect(Client.Start.RemotServerIP, Client.Start.RemotServerPort);
                }
                s.Send(p.MarkPack(MIP, MLevel, MLogger, MLogMessage, MException, MAddTime));
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            finally
            {
                s.Shutdown(SocketShutdown.Both);
                s.Disconnect(true);
                s.Close();
            }
        }
        #endregion
    }

    /// <summary>
    /// 服务器端写日志操作
    /// </summary>
    public class SvrWriteLog
    {
        private static object locker = new object();
        private StreamWriter sw = null;

        #region 缓存DB日志处理
        /// <summary>
        /// 缓存DB日志处理
        /// </summary>
        public void WirteCacheLogDB()
        {
            string[] TranSQL = null;
            try
            {
                TranSQL = LogCacheTxtDB();
                if (TranSQL != null)
                {
                    MSSQL.SqlOp DB = new MSSQL.SqlOp();
                    DB.ExecuteSqlTran(TranSQL, 30);
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            finally
            {
                TranSQL = null;
            }
        }
        private string[] LogCacheTxtDB()
        {
            string[] TranSQL = null;
            try
            {
                lock (locker)
                {
                    TranSQL = new string[DataEntity.SvrData.se.Count];
                    for (int i = 0; i < DataEntity.SvrData.se.Count; i++)
                    {
                        TranSQL[i] = "insert into tLog (IP,Level,Logger,LogMessage,Exception,AddTime,Interval,Count) values ('" + DataEntity.SvrData.se[i].IP + "','" + DataEntity.SvrData.se[i].Level + "','" + DataEntity.SvrData.se[i].Logger + "','" + DataEntity.SvrData.se[i].LogMessage + "','" + DataEntity.SvrData.se[i].Exception + "','" + DataEntity.SvrData.se[i].AddTime + "'," + DataEntity.SvrData.se[i].Interval + "," + DataEntity.SvrData.se[i].Count + ")";
                    }
                    DataEntity.SvrData.se.RemoveRange(0, DataEntity.SvrData.se.Count);
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            return TranSQL;
        }
        /// <summary>
        /// 缓存DB日志处理
        /// </summary>
        public void WirteCacheLogDB(List<DataEntity.CliErrEntity> ee)
        {
            string[] TranSQL = null;
            try
            {
                TranSQL = LogCacheTxtDB(ee);
                if (TranSQL != null)
                {
                    MSSQL.SqlOp DB = new MSSQL.SqlOp();
                    DB.ExecuteSqlTran(TranSQL, 30);
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            finally
            {
                TranSQL = null;
            }
        }
        private string[] LogCacheTxtDB(List<DataEntity.CliErrEntity> ee)
        {
            string[] TranSQL = null;
            try
            {
                TranSQL = new string[ee.Count];
                for (int i = 0; i < ee.Count; i++)
                {
                    TranSQL[i] = "insert into tLog (IP,Level,Logger,LogMessage,Exception,AddTime,Interval,Count) values ('" + ee[i].IP + "','" + ee[i].Level + "','" + ee[i].Logger + "','" + ee[i].LogMessage + "','" + ee[i].Exception + "','" + ee[i].AddTime + "'," + ee[i].Interval + "," + ee[i].Count + ")";
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            return TranSQL;
        }
        #endregion

        #region 缓存文件日志处理
        /// <summary>
        /// 缓存文件日志处理
        /// </summary>
        public void WirteCacheLogFile()
        {
            lock (locker)
            {
                string FileTxt = "";
                for (int i = 0; i < DataEntity.SvrData.se.Count; i++)
                {
                    FileTxt += "时间-" + DataEntity.SvrData.se[i].AddTime + "间隔" + DataEntity.SvrData.se[i].Interval / 1000 + "秒，发送信息" + DataEntity.SvrData.se[i].Count + "条" + "：" + DataEntity.SvrData.se[i].IP + "-" + DataEntity.SvrData.se[i].Logger + "-" + "记录" + DataEntity.SvrData.se[i].Level + "信息内容" + DataEntity.SvrData.se[i].LogMessage + DataEntity.SvrData.se[i].Exception;
                }
                DataEntity.SvrData.se.RemoveRange(0, DataEntity.SvrData.se.Count);
                if (FileTxt != "")
                {
                    sw = new StreamWriter(Server.Start.LogFilePath + @"\" + DateTime.Now.ToString("yyyymmddhh") + ".log", true, Encoding.Default);
                    try
                    {
                        sw.Write(FileTxt);
                    }
                    catch (Exception ex)
                    {
                        throw (new Exception(ex.Message));
                    }
                    finally
                    {
                        sw.Close();
                        sw.Dispose();
                    }
                }
            }
        }
        /// <summary>
        /// 缓存文件日志处理
        /// </summary>
        public void WirteCacheLogFile(List<DataEntity.CliErrEntity> ee)
        {
            string FileTxt = "";
            for (int i = 0; i < ee.Count; i++)
            {
                FileTxt += "时间-" + ee[i].AddTime + "间隔" + ee[i].Interval / 1000 + "秒，发送信息" + ee[i].Count + "条" + "：" + ee[i].IP + "-" + ee[i].Logger + "-" + "记录" + ee[i].Level + "信息内容" + ee[i].LogMessage + ee[i].Exception;
            }
            if (FileTxt != "")
            {
                sw = new StreamWriter(Server.Start.LogFilePath + @"\" + DateTime.Now.ToString("yyyymmddhh") + ".log", true, Encoding.Default);
                try
                {
                    sw.Write(FileTxt);
                }
                catch (Exception ex)
                {
                    throw (new Exception(ex.Message));
                }
                finally
                {
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
        #endregion
    }
}
